package com.zsh.wx_account1.util;

import com.zsh.wx_account1.entity.AccessToken;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.util.ObjectUtils;

/**
 * 获取 Access token的工具类
 * @Author ZhaoShuHao
 * @Date 2023/8/23 9:44
 */
public class TokenUtil {
    //自己的公众号信息
    //测试号
    private static final String APP_ID = "wx43f47bd394a23feb";
    private static final String APP_SECRET = "1a29d7b96b7403c99b20d563057a10c8";
    //自己的公众号
   /* private static final String APP_ID = "wxd0ea52fb7073863b";
    private static final String APP_SECRET = "331bbdc569158b41d2589b618db928d1";*/
    private static AccessToken accessToken = new AccessToken();
    public static void main(String[] args) {

    //{"access_token":"63_8R2EcPuM3dz_D81Q2FBiSfgrlwokafQloAU33iFhHIbjabRFtC_thRqk7VOkMbarQ8lA9yyq2pgwh4pc6P-5qQutc6WWMLwFafIR6ZaLkB299OJU78npFt--I0ACXCiACAHCH","expires_in":7200}
        System.out.println(getAccessToken());
    }
    private static void getToken(){
        String url = String.format("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
                APP_ID,
                APP_SECRET);
        String result = HttpUtil.doGet(url);
        if(StringUtils.isNotBlank(result)){
            JSONObject jsonObject = JSONObject.fromObject(result);
            String token = jsonObject.getString("access_token");
            long expiresIn = jsonObject.getLong("expires_in");
            accessToken.setToken(token);
            accessToken.setExpireTime(expiresIn);
        }
    }
    /**
     * 获取AccessToken
     * @return
     */
    public static String getAccessToken(){
        //如果accessToken为空或者超时，都重新获取token
        if(ObjectUtils.isEmpty(accessToken) || accessToken.isExpired()){
            getToken();
        }
        return accessToken.getToken();
    }
}
